<?php

namespace App\Service;

use App\Common\Func;
use App\Enums\AssetJournalBusinessTypeEnum;
use App\Exceptions\ApiException;
use App\Http\BizServices\Asset\AddAssetService;
use App\Models\UserActiveModel;
use Illuminate\Support\Facades\Cache;

class UserActiveService
{

    /**
     * @var UserActiveModel
     */
    private UserActiveModel $usersActiveModel;

    public function __construct(UserActiveModel $usersActiveModel)
    {
        $this->usersActiveModel = $usersActiveModel;
    }

    /**
     * @param int $userId
     * @return bool
     * @throws ApiException
     */
    public function addActive(int $userId)
    {
        $rdsKey = 'add_active:' . $userId;
        $lock = Cache::lock($rdsKey, 300);
        if (!$lock->get()) {
            throw new ApiException('', '10001');
        }
        try {
            $now = now();
            $existLog = $this->usersActiveModel->existLog($userId, $now->startOfDay()->toDateTimeString(), $now->endOfDay()->toDateTimeString());
            if ($existLog) {
                return true;
            }
            $usersActiveModel = new UserActiveModel();
            $usersActiveModel->user_id = $userId;
            $save = $usersActiveModel->save();
            if ($save) {
                AddAssetService::loginAddScore($usersActiveModel, AssetJournalBusinessTypeEnum::LOGIN);
            }
            return $save;
        } catch (\Exception $e) {
            Func::logError(compact('userId'), $e->getMessage(), '添加活跃记录');
            throw new ApiException("添加活跃记录失败");
        } finally {
            $lock->release();
        }
    }
}
